{% extends "base/base_alert.html" %}

{% block style %}
    <link href="/static/uploadify/uploadify.css" type="text/css" rel="stylesheet"/>
    <link href="/static/uploadify/Jcrop/css/jquery.Jcrop.min.css" type="text/css" rel="stylesheet"/>
    <style type="text/css">
        /* Apply these styles only when #preview-pane has
           been placed within the Jcrop widget */
        .jcrop-holder #preview-pane {
            display: block;
            position: absolute;
            z-index: 2000;
            top: 10px;
            right: -280px;
            padding: 6px;
            border: 1px rgba(0, 0, 0, .4) solid;
            background-color: white;

            -webkit-border-radius: 6px;
            -moz-border-radius: 6px;
            border-radius: 6px;

            -webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
            -moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
            box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
        }

        #upload_file {
            top: 10px;
            float: left;
        }

        #id_span_msg {
            /*       margin-left:10%; */
            float: left;

        }

        /*   #deletefile { */
        /*       margin-left:5%; */
        /*   } */
        #imgdiv {
            clear: both;
        }

        #img_span_delete {
            padding-top: 13px;
            float: left;

        }

        #upload_file-queue {
            float: left;
        }

        #upload_file-button {
            border-radius: 3px;

        }

        #showimg {
            padding: 0;
            margin: 0;
        }

        /* The Javascript code will set the aspect ratio of the crop
           area based on the size of the thumbnail preview,
           specified here */
    </style>
{% endblock %}
{% block container %}


    <div id="container">
        <p id="inputDiscript">只支持psd,jpeg,png,gif,webp,tiff,bmp的图片格式上传</p>
        <!--     <a class="upload-btn" href="javascript:$('#upload_file').click();"> -->
        <!--         <img src="/static/uploadify/choose-up.png">  -->
        <!--     </a> -->
        <div>
            <img src="/static/image/choose-up.jpg" style="position: absolute"/>
            <input type="file" value="选择文件" id="upload_file" style="display: block;opacity: 0; position: absolute"/>
        </div>
        <div id="img_span_delete" style="margin-left: 120px;">
            <span id="id_span_msg"></span>
            <span class="graybtn" style="display:none;">
        <a id="deletefile" href="javascript:;" onclick="delete_file()" class="btn btn-default btn-sm">删 除</a>
        </span>
        </div>
    </div>
    <br/><br/>

    <div id="imgdiv" style="display: block;">
        <img class="showimg" id="showimg" width="500px" src="" alt=""/>

    </div>

    <div id="preview-pane">
        <div class="preview-container">
            <img src="" class="jcrop-preview" alt=""/>
        </div>
    </div>

    <input id="cropbtn" type="button" value="button" style="display:none;"/>
    <p id="cropurl" style="display:none;"></p>

{% endblock %}

{% block footjs %}
    <script src="/static/uploadify/jquery-1.9.1.min.js"></script>
    <!-- <script src="//cdn.bootcss.com/jquery/1.9.1/jquery.min.js" type="text/javascript"></script> -->
    <script src="/static/uploadify/Jcrop/js/jquery.Jcrop.min.js" type="text/javascript"></script>

    <!--引入Pupload js插件 调试需安moxie.js 再 plupload.dev.js引入-->
    <script src="/static/uploadify/plupload-2.1.8/js/moxie.js" type="text/javascript"></script>
    <script src="/static/uploadify/plupload-2.1.8/js/plupload.dev.js" type="text/javascript"></script>
    <script src="/static/uploadify/plupload-2.1.8/js/jquery.ui.plupload/jquery.ui.plupload.js"
            type="text/javascript"></script>
    <!--引入qiniu.js-->
    <script src="/static/uploadify/qiniu.js" type="text/javascript"></script>

    <script type="text/javascript">
        // function delete_file(){
        //     if (!document.getElementById) return false;
        //     if (!document.getElementById('id_span_msg')) return false;
        //     if (!document.getElementById('upload_file')) return false;
        //     if (!document.getElementById('img_span_delete')) return false;
        //     if (!document.getElementById('showimg')) return false;
        //     if (!document.getElementsByTagName) return false;
        //     if (!document.getElementsByTagName('span')) return false;
        //     document.getElementById('id_span_msg').innerHTML = '';
        // //     document.getElementById('upload_file').style.display = 'block';
        //     document.getElementById('img_span_delete').getElementsByTagName('span')[1].style.display = 'none';

        //     var imgdiv = document.getElementById('imgdiv');
        //     imgdiv.style.display = 'none';
        //     var imgs = imgdiv.getElementsByTagName('img');
        //     for(var i=0; i<imgs.length; i++){
        //         imgs[i].setAttribute('src', '');
        //     }
        //     return false;
        // }

        //父页面传来的宽高
        var p_width = Number(sessionStorage.getItem('width'));
        var p_height = Number(sessionStorage.getItem('height'));
        //宽200高随意
        var width = 200;
        var height = 0;//高=0 的不剪裁
        if (p_width && p_height) {
            height = 200 / p_width * p_height;
        }

        $(document).ready(function () {
            imgeMogr2Link();
            //设置预览框的大小.根据高宽

            //ajax请求domain域名
            $.get('{% url 'upload_file:qiniu-domain' %}', function (data, statusText) {
                if (statusText == 'success') {
                    window.domain = data.domain;
                    initQiniu();
                }
            });
            function initQiniu() {
                $(".preview-container").css({width: width, height: height, overflow: "hidden"});
                var uploader = Qiniu.uploader({
                    runtimes: 'html5,flash,html4',    //上传模式,依次退化
                    browse_button: 'upload_file',       //上传选择的点选按钮，**必需**
                    uptoken_url: '/upload_file/upload_token/',
                    //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
                    // uptoken : '<Your upload token>',
                    //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
                    unique_names: true,
                    // 默认 false，key为文件名。若开启该选项，SDK会为每个文件自动生成key（文件名）
                    // save_key: true,
                    // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
                    domain: window.domain,
                    //bucket 域名，下载资源时用到，**必需**
                    //container: 'container',           //上传区域DOM ID，默认是browser_button的父元素，
                    max_file_size: '2mb',           //最大文件体积限制
                    flash_swf_url: '/static/uploadify/Moxie.swf',  //引入flash,相对路径
                    max_retries: 3,                   //上传失败最大重试次数
                    dragdrop: true,                   //开启可拖曳上传
                    drop_element: 'container',        //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
                    chunk_size: '4mb',                //分块上传时，每片的体积
                    auto_start: true,                 //选择文件后自动上传，若关闭需要自己绑定事件触发上传
                    filters: [                       //过滤文件
                        {title: "Image files", extensions: "psd,jpeg,jpg,png,gif,webp,tiff,bmp"}
                    ],


                    multi_selection: false, //设置上传多张图片


                    //resize : {width : 100, height : 100, quality : 90},     //生成缩略图

                    init: {
                        'FilesAdded': function (up, files) {
                            plupload.each(files, function (file) {
                                // 文件添加进队列后,处理相关的事
                                document.getElementById('id_span_msg').innerHTML = '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
                            });
                        },
                        'BeforeUpload': function (up, file) {

                        },
                        'UploadProgress': function (up, file) {
                            // 每个文件上传时,处理相关的事情
                            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                        },
                        'FileUploaded': function (up, file, info) {
                            // 每个文件上传成功后,处理相关的事情
                            // 其中 info 是文件上传成功后，服务端返回的json，形式如
                            // {
                            //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                            //    "key": "gogopher.jpg"
                            //  }
                            // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
                            var domain = up.getOption('domain');
                            var res = $.parseJSON(info);
                            var sourceLink = 'http://' + domain + '/' + res.key;   //获取上传成功后的文件的Url

                            //               var showing = document.getElementById('showimg');
                            //               showing.setAttribute('src',sourceLink);
                            var previewDiv = document.getElementById('preview-pane');
                            var previewPic = previewDiv.getElementsByTagName('img')[0];
                            previewPic.setAttribute('src', sourceLink);
                            //删除后
                            var imgdiv = document.getElementById('imgdiv');
                            imgdiv.style.display = 'block';
                            var imgs = imgdiv.getElementsByTagName('img');
                            for (var i = 0; i < imgs.length; i++) {
                                imgs[i].setAttribute('src', sourceLink);
                            }
                            window.key = res.key;
                            window.sourceLink = sourceLink;
                            window.domain = domain;
                            $("#cropurl").text(sourceLink);//返回上页面的链接

                        },
                        'Error': function (up, err, errTip) {
                            //上传出错时,处理相关的事情
                        },
                        'UploadComplete': function () {
                            //队列文件处理完毕后,处理相关的事情
                        }
                        /*
                         'Key': function(up, file) {
                         // 若想在前端对每个文件的key进行个性化处理，可以配置该函数
                         // 该配置必须要在 unique_names: false , save_key: false 时才生效
                         //当save_key和unique_names设为false时，该方法将被调用
                         var key = '';
                         $.ajax({
                         url:'/get_key/',
                         type:'GET',
                         async: false,//这里应设置为同步的方式
                         success: function(data) {
                         var ext = Qiniu.getFileExtension(file.name);    //获取扩展名
                         key = data + '.' + ext;
                         },
                         cache: false
                         });
                         // do something with key here
                         return key;

                         }
                         */


                    }
                });
                //绑定 上传完成事件
                uploader.bind('FileUploaded', function () {
                    var showimg = document.getElementById('showimg');
                    //判断页面图片是否加载完毕
                    if (!showimg.complete) {
                        showimg.addEventListener('load', function () {
                            if (height) {
                                LoadImage(window.sourceLink, display_width);
                                jcrop_cutimg();
                            }
                        })
                    }
                });
            }

        });

        //创建裁剪对象
        function jcrop_cutimg() {
            $preview = $('#preview-pane');
            $pcnt = $('div#preview-pane .preview-container');
            $pimg = $('div#preview-pane .preview-container img');

            xsize = $pcnt.width();
            ysize = $pcnt.height();

            $('#showimg').Jcrop({
                onChange: updatePreview,       //改变选项框事件
                onSelect: updatePreview,       //选择选项框事件
                aspectRatio: xsize / ysize     //设置选项框长宽比
            }, function () {
                // Use the API to get the real image size
                var bounds = this.getBounds();
                boundx = bounds[0];
                boundy = bounds[1];
                // Store the API in the jcrop_api variable
                jcrop_api = this;
                //默认选择框
                var x1 = (boundx - width) / 2;
                var y1 = (boundy - height) / 2;
                var x2 = (boundx - width) / 2 + width;
                var y2 = (boundy - height) / 2 + height;
                jcrop_api.animateTo([x1, y1, x2, y2]);//初始设置为居中
                // Move the preview into the jcrop container for css positioning
                $preview.appendTo(jcrop_api.ui.holder);

            });
        }
        function updatePreview(c) {
            if (parseInt(c.w) > 0) {
                var rx = xsize / c.w;
                var ry = ysize / c.h;
                //      var img_top_margin,img_left_margin,img_width,img_height;//最后剪裁使用的4个变量
                //      img_top_margin=c.y;
                //          img_left_margin=c.x;
                //          img_width=c.w;
                //          img_height=c.h;
                //尺寸赋值 img_left_margin,img_top_margin,img_width,img_height,像素:Number(width),Number(height)
                //      $("#cut_size").val(c.x+","+c.y+","+c.w+","+c.h+","+p_width+","+p_height);
                nowx = $('#showimg').width();
                nowy = $('#showimg').height();
                window.x = Math.round(c.x * (turthx / nowx));
                window.y = Math.round(c.y * (turthy / nowy));
                window.w = Math.round(c.w * (turthx / nowx));
                window.h = Math.round(c.h * (turthy / nowy));
                //预览框显示
                $pimg.css({
                    width: Math.round(rx * boundx) + 'px',
                    height: Math.round(ry * boundy) + 'px',
                    marginLeft: '-' + Math.round(rx * c.x) + 'px',
                    marginTop: '-' + Math.round(ry * c.y) + 'px'
                });
            }
        }

        function imgeMogr2Link() {
            var subtn = document.getElementById('cropbtn');
            subtn.onclick = function () {
                var imgLink = Qiniu.imageMogr2({
                    'auto-orient': true,  // 布尔值，是否根据原图EXIF信息自动旋正，便于后续处理，建议放在首位。
                    strip: true,               // 布尔值，是否去除图片中的元信息
                    // thumbnail: '1x1',   // 缩放操作参数
                    crop: '!' + String(window.w) + 'x' + String(window.h) + 'a' + String(window.x) + 'a' + String(window.y),   // 裁剪操作参数
                    gravity: 'NorthWest',    // 裁剪锚点参数
                    quality: 100,  // 图片质量，取值范围1-100
                    //    rotate: 20,   // 旋转角度，取值范围1-360，缺省为不旋转。
                    format: 'png',// 新图的输出格式，取值范围：jpg，gif，png，webp等
                    //    blur:'3x5'    // 高斯模糊参数
                }, window.key);
                $("#cropurl").text('http://' + imgLink);
                //         var testurl = document.createTextNode(imgLink);
                //         document.getElementById('testurl').appendChild(testurl);
                //         var ele_key = document.getElementById('key');
                //         ele_key.name = 'key';
                //         ele_key.value = imgLink;

                /*
                 var randomNumber = randomNum(4);      //产生4位随机数
                 alert(typeof randomNumber);
                 var myTime = new Date().getTime();
                 var newKey = String(myTime) + randomNumber;
                 var accessKey = "nyHwH2aGckUsKS5mgZXIpsfyAMAgyiNb42Zv8sTS";
                 var secretKey = "T9eKbgoe8HgFG-zh6aWncfXDurxRlMbZXl0zsmBp";

                 var entryURI = 'heiomano' + ':' + newKey;
                 //        var entryURI = 't-test:Ship-thumb-200.jpg';
                 alert('entry>>>>'+entryURI);
                 var encodedEntryURI = Qiniu.URLSafeBase64Encode(entryURI);
                 alert('encodedEntryURI>>>'+ encodedEntryURI);
                 var newurl = imgLink + '|saveas/'+encodedEntryURI;
                 alert(newurl);
                 var sign = CryptoJS.HmacSHA1(newurl,secretKey);
                 alert('sign>>>>'+sign);
                 var encodedSign = Qiniu.URLSafeBase64Encode(sign);
                 alert('encodedSign>>>'+encodedSign);
                 var finalURL = newurl + '/sign/' + accessKey + ':' + encodedSign;
                 alert(finalURL);
                 document.write(finalURL);
                 */
            }
        }

        function randomNum(n) {
            var random_number = '';
            for (var i = 0; i < n; i++) {
                random_number = random_number + Math.floor(Math.random() * 10);
            }
            return random_number
        }

        //图片真实大小
        function LoadImage(imgSrc, callback) {
            var image = new Image();
            image.src = imgSrc;
            if (image.complete) {
                callback(image);
                image.onload = function () {
                };
            } else {
                image.onload = function () {
                    callback(image);
                    // clear onLoad, IE behaves erratically with animated gifs otherwise
                    image.onload = function () {
                    };
                };
                image.onerror = function () {
                    alert("Could not load image.");
                }
            }
        }
        function display_width(image) {
            turthx = image.width;
            turthy = image.height;
        }

        // domain 为七牛空间（bucket)对应的域名，选择某个空间后，可通过"空间设置->基本设置->域名设置"查看获取
        // uploader 为一个plupload对象，继承了所有plupload的方法，参考http://plupload.com/docs

    </script>





{% endblock %}

